package com.codeplex.jtfscli.util;

import java.util.StringTokenizer;

import com.microsoft.tfs.core.TFSTeamProjectCollection;
import com.microsoft.tfs.core.clients.versioncontrol.workspacecache.CachedWorkspace;
import com.microsoft.tfs.core.config.ConnectionInstanceData;
import com.microsoft.tfs.core.config.DefaultConnectionAdvisor;
import com.microsoft.tfs.core.persistence.PersistenceStore;
import com.microsoft.tfs.core.persistence.VersionedVendorFilesystemPersistenceStore;
import com.microsoft.tfs.core.profiles.Profile;
import com.microsoft.tfs.core.profiles.ProfileProperties;

/**
 * Generates connections to TFS. We use this so we have a single point to
 * configure the persistence.
 * 
 * @author jack
 * 
 */
public class TFSConnectionFactory {
	public Profile createProfile(final String server,
			final String usernameAndDomain, final String password) {
		final Profile profile = new Profile();
		final StringTokenizer st = new StringTokenizer(usernameAndDomain, "\\");
		profile.addValue(ProfileProperties.USER_DOMAIN, st.nextToken());
		profile.addValue(ProfileProperties.USER_NAME, st.nextToken());
		profile.addValue(ProfileProperties.PASSWORD, password);
		profile.addValue(ProfileProperties.SERVER_URL, server);
		return profile;
	}

	public TFSTeamProjectCollection createConnection(final String server,
			final String usernameAndDomain, final String password) {
		return new TFSTeamProjectCollection(createProfile(server,
				usernameAndDomain, password), new JtfscliConnectionAdvisor(
				getDefaultPersistenceStore()));
	}

	public TFSTeamProjectCollection createConnectionForWorkspace(
			final CachedWorkspace workspace) {
		return new TFSTeamProjectCollection(workspace.getProfile(),
				new JtfscliConnectionAdvisor(getDefaultPersistenceStore()));
	}

	public PersistenceStore getDefaultPersistenceStore() {
		return new VersionedVendorFilesystemPersistenceStore("jtfscli",
				"jtfscli", "1.0");
	}

	private static class JtfscliConnectionAdvisor extends
			DefaultConnectionAdvisor {
		final PersistenceStore ps;

		public JtfscliConnectionAdvisor(final PersistenceStore ps) {
			this.ps = ps;
		}

		@Override
		public PersistenceStore getBasePersistenceStore(
				ConnectionInstanceData instanceData) {
			return ps;
		}
	}
}
